<template>
  <view class="forget">
    <view class="tab p90">手机号验证</view>
    <view class="h20"></view>
    
    <!-- 验证手机号  -->
    <view class="code p90">
      <view class="box" :class="{active: !isAct}">
        <view class="label">手机号</view>
        <view class="inpt">
          <input class="input" type="number" @focus="getActive(0)" v-model="mobile" maxlength="11" placeholder="请输入手机号">
        </view>
      </view>
      <view class="box" :class="{active: isAct}">
        <view class="label">验证码</view>
        <view class="inpt"><input type="number" maxlength="6" @focus="getActive(1)" placeholder="请输入验证码" v-model="mobileCode"></view>
        <view class="line">
          <span v-if="!timer" @click="validForm(1)">获取验证码</span>
          <span v-else>重发{{count}}s</span>
        </view>
      </view> 
      <button class="sub-btn" @click="validForm(2)">完成登录</button>
    </view>
    <!--  -->
  </view>
</template>
  
<script>
import { SendCode } from '@/service/common/code.service.js'
import { decideEnv, getUrlParam } from '@/unit/common.js';
import { wxBindPhoneApi, alipayBindPhoneApi } from '@/service/login/login.service.js'
import formValid from '@/unit/graceChecker.js'
import md5 from 'js-md5';
import qs from 'qs';

export default {
  data () {
    return {
      isAct: false,
      count: 60,
      hasGetCode: false,
      timer: null,
      mobile: '',
      password: '',
      mobileCode: '',
      otherData: {
        openId: '',
        sex: '',
        unionId: '',
        alipayUserId: ''
      }
    }
  },
  methods: {
    getActive (index) {
      this.isAct = index == 0;
    },
    validForm (type) {
      let rule = [];
      let params = {};
      rule = type == 1 ? rule = rule.concat([
        {name:'mobile', checkType: 'notnull', checkRule: '',  errorMsg:'请输入手机号'},
        {name:'mobile', checkType: 'phoneno', checkRule: '',  errorMsg:'请输入正确的手机号'}
      ]) : [
        {name:'mobile', checkType: 'notnull', checkRule: '',  errorMsg:'请输入手机号'},
        {name:'mobile', checkType: 'phoneno', checkRule: '',  errorMsg:'请输入正确的手机号'},
        {name:'mobileCode', checkType: 'notnull', checkRule: '',  errorMsg:'请输入验证码'},
        {name:'mobileCode', checkType: 'int', checkRule: '5,5',  errorMsg:'请输入正确的验证码'}
      ];
      params = type == 1 ? {
        mobile: this.mobile
      } : {
        mobile: this.mobile,
        mobileCode: this.mobileCode
      };
      var checkRes = formValid.check(params, rule);
      if (checkRes) {
        type == 1 ? this.getCode() : (decideEnv() && decideEnv() == 'wx') ? this.loginInWX() : this.loginInAlipay();
      } else {
        uni.showToast({ title: formValid.error, icon: "none" });
      }
    },
    loginInAlipay () { // Alipay登录
      let params = Object.assign(this.otherData, {
        mobile: this.mobile,
        mobileCode: this.mobileCode
      });
      alipayBindPhoneApi(params, res => {
        if (res.status == 0) {
          uni.setStorageSync('freeStore', res.data.freeStore);
          uni.showToast({
            title: '登陆成功！',
            duration: 2000,
            success: () => {
              uni.setStorage({
                key: 'user_token',
                data: res.data.token,
                success: () => {
                  if (res.data.rank < 2 && res.data.freeStore == 0) {
                    setTimeout(() => {
                      uni.reLaunch({
                        url: '/pages/join/result'
                      })
                    }, 2000);
                  } else if (res.data.rank < 2 && res.data.freeStore == 1) {
                    setTimeout(() => {
                      uni.reLaunch({
                        url: '/pages/freeStore/result'
                      })
                    }, 2000);
                  } else {
                    this.$store.dispatch('getUserInfo').then(res => {
                      setTimeout(() => {
                        if (this.from) {
                          // #ifdef H5
                          window.open(decodeURIComponent(this.from), '_self');
                          // #endif
                        } else {
                          uni.switchTab({
                            url: '/pages/index/index'
                          })
                        }
                      }, 1500)
                    });
                    
                  }
                }
              });
            }
          });
        }
      }, null, {showErrorMsg: true});
    },
    loginInWX () { // WX登录
      let params = Object.assign(this.otherData, {
        mobile: this.mobile,
        mobileCode: this.mobileCode
      });
      let inviteId = uni.getStorageSync('userInvite')
      if (inviteId) {
        params.inviteId = inviteId;
      }
      wxBindPhoneApi(params, res => {
        if (res.status == 0) {
          uni.removeStorageSync('userInvite');
          uni.setStorageSync('freeStore', res.data.freeStore);
          uni.showToast({
            title: '登陆成功！',
            duration: 2000,
            success: () => {
              uni.setStorage({
                key: 'user_token',
                data: res.data.token,
                success: () => {
                  if (res.data.rank < 2 && res.data.freeStore == 0) {
                    setTimeout(() => {
                      uni.reLaunch({
                        url: '/pages/join/result'
                      })
                    }, 2000);
                  } else if (res.data.rank < 2 && res.data.freeStore == 1) {
                    setTimeout(() => {
                      uni.reLaunch({
                        url: '/pages/freeStore/result'
                      })
                    }, 2000);
                  } else {
                    this.$store.dispatch('getUserInfo').then(res => {
                      setTimeout(() => {
                        if (this.from) {
                          // #ifdef H5
                          window.open(decodeURIComponent(this.from), '_self');
                          // #endif
                        } else {
                          uni.switchTab({
                            url: '/pages/index/index'
                          })
                        }
                      }, 1500)
                    });
                  }
                }
              });
            }
          });
        }
      }, null, {showErrorMsg: true});
    },
    getCode () { // 获取验证码
      SendCode({
        mobile: this.mobile,
        type: decideEnv() && decideEnv() == 'wx' ? 1 : 5,
      }, (res) => {
        if (res.status == 0) {
          uni.showToast({
            title: '验证码发送成功！',
            icon: 'none'
          });
          this.countDown();
          _self.hasGetCode = true;
        } else {
          uni.showToast({
            title: res.msg,
            icon: 'none'
          });
        };
      })
    },
    countDown () { // 倒计时
      const TIME_COUNT = 60;
      if (!this.timer) {
        this.count = TIME_COUNT;
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--;
          } else {
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000)
      }
    }
  },
  onShow () {
    // 
  },
  onLoad (option) {
    if (option) {
      this.otherData.openId = option.openId;
      this.otherData.unionId = option.unionId;
      this.otherData.alipayUserId = option.alipayUserId;
    }
  } 
}
</script>

<style scoped lang="scss">
.p90 {
  padding: 0 90rpx;
}
.h20 {
  width: 100%;
  height: 20rpx;
  background-color: #FAFAFA;
  margin-top: 15rpx;
}
.forget {
  height: 100vh;
  color: #333333;
  background-color: #FFFFFF;
  .tab {
    padding-top: 146rpx;
    font-size: 36rpx;
    text-align: left;
    font-weight: bold;
  }
  .code {
    .hint {
      text-align: center;
      font-size: 24rpx;
      color: #999999;
      margin-top: 17rpx;
    }
  }
  .setNewPwd {
    margin-top: 23rpx;
    .text {
      font-size: 24rpx;
      color: #999999;
    }
  }
  
  .sub-btn {
    margin-top: 112rpx;
    height: 70rpx;
    line-height: 70rpx;
    background: #636363;
    border-radius: 10rpx;
    color: #F6DA99;
    font-size: 30rpx;
    text-align: center;
    &.active {
      background-color: #434343;
      color: #F6DA99;
    }
  }
}
.box {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 40rpx 0;
  font-size: 28rpx;
  border-bottom: 1rpx solid #E1E1E1;
  &.active {
    border-color: #F6DA99;
  }
  .name {
    width: 82rpx;
    font-size: 28rpx;
  }
 
  .inpt {
    width: 320rpx;
    margin-left: 40rpx;
    input{
      font-size: 28rpx;
      font-weight:500;
    }
  }
  .clear-margin {
    margin: 0px;
  }
  
  .code-input {
    .uni-input-placeholder {
      font-size: 24rpx;
    }
  }
  .line {
    // width: 120rpx;
    font-size: 24rpx;
  }
}

.setNewPwd-title {
  font-size: 24rpx;
  font-weight:500;
  color: #999999;
}
.setNewPwd-phone {
  font-size: 24rpx;
  font-weight:500;
  line-height: 40rpx;
  color: #999999;
}

</style>
